package com.juzipi.demo.aspect;


import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


@Aspect
@Component
public class AopLog {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    //线程局部变量，用于解决多线程中相同的变量的访问冲突
//    ThreadLocal<Long> startTime = new ThreadLocal<>();
    long start = System.currentTimeMillis();

    @Pointcut("execution(* com.juzipi.demo.controller.*.*(..))")
    public void log(){

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        //接收到请求，记录请求内容
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        //记录下请求内容
        String url = request.getRequestURI();
        String method = request.getMethod();
        String ip = request.getRemoteAddr();
        String queryString = request.getQueryString();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        logger.info("URL:"+url);
        logger.info("Http方法:"+method);
        logger.info("IP地址:"+ip);
        logger.info("参数:"+queryString);
        logger.info("类的方法:"+classMethod);

    }

    @AfterReturning(pointcut = "log()",returning = "retObject")
    public void doAfterReturning(Object retObject){
        //处理完请求，返回内容
//        logger.info("应答值："+retObject.toString());
        System.out.println();
        long end = System.currentTimeMillis();
        logger.info("费时："+(end - start)+"毫秒");

    }
    //方法抛出异常退出时执行的通知
    @AfterThrowing(pointcut = "log()",throwing = "e")
    public void addAfterThrowingLogger(JoinPoint joinPoint,Exception e){
        logger.error("执行"+"异常",e);
    }


}
